<!-- 2017-12-4 14:24:12 | 修改 木遥（微信:  http://marsgis.cn/weixin.html ） -->
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0" />
    <meta name="apple-touch-fullscreen" content="yes" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="x5-fullscreen" content="true" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />

    <!-- 标题及搜索关键字 -->
    <meta name="keywords" content="火星科技,cesium,3D,GIS,marsgis,三维,地球,地图,开发,框架,系统,示例,资料,模型,离线,外包,合肥,安徽,中国" />
    <meta
      name="description"
      content="火星科技 合肥火星 合肥火星科技 合肥火星科技有限公司 leaflet leaflet框架 leaflet开发 cesium cesium开发 cesium框架 三维 地球 模型  gis marsgis 地图离线 地图开发 地图框架 地图外包 框架 开发 外包  地图离线 二维地图 三维地图 全景漫游 地理信息系统 云GIS 三维GIS GIS平台 WebGIS"
    />

    <link rel="shortcut icon" type="image/x-icon" href="http://mars3d.cn/favicon.ico" />
    <title>卫星过境 | Mars3D | 三维地图 | 火星科技 | 合肥火星科技有限公司</title>

    <script
      type="text/javascript"
      src="../lib/include-lib.js"
      libpath="../lib/"
      include="jquery,font-awesome,jedate,web-icons,bootstrap,bootstrap-table,layer,toastr,nprogress,haoutil,turf,mars3d,mars3d-space"
    ></script>
    <link href="css/style.css" rel="stylesheet" />
  </head>

  <body class="dark">
    <!--加载前进行操作提示，优化用户体验-->
    <div id="mask" class="signmask" onclick="removeMask()"></div>

    <div id="mars3dContainer" class="mars3d-container"></div>

    <!-- 面板 -->
    <div class="infoview">
      <table class="mars-table">
        <tr>
          <td class="nametd">过境区域：</td>
          <td>
            <input type="button" class="btn btn-primary" value="框选" id="drawRectangle" />
            <input type="button" class="btn btn-primary" value="圆形" id="drawCircle" />
            <input type="button" class="btn btn-primary" value="多边形" id="drawPolygon" />
            <input type="button" class="btn btn-primary" value="清除" id="drawClear" />
          </td>
        </tr>

        <tr>
          <td class="nametd">开始时间：</td>
          <td>
            <input type="text" class="form-control" id="txtStartTime" placeholder="YYYY-MM-DD" />
          </td>
        </tr>
        <tr>
          <td class="nametd">结束时间：</td>
          <td>
            <input type="text" class="form-control" id="txtEndTime" placeholder="YYYY-MM-DD" />
          </td>
        </tr>
        <tr>
          <td class="nametd"></td>
          <td>
            <input type="button" class="btn btn-primary" value="开始分析" onclick="startFX()" />
            <input type="button" class="btn btn-primary" value="清除" onclick="clearResult();" />
          </td>
        </tr>
      </table>

      <table id="table"></table>
    </div>

    <script src="./js/common.js"></script>
    <script type="text/javascript">
      'use script' //开发环境建议开启严格模式

      var map
      var graphicLayer

      var tleArr
      var drawGraphic
      var $table

      function initMap(options) {
        //合并属性参数，可覆盖config.json中的对应配置
        var mapOptions = mars3d.Util.merge(options, {
          scene: {
            center: {
              y: 21.102844,
              x: 108.441169,
              z: 4426844.43,
              heading: 356.4,
              pitch: -76.9,
              roll: 0.1,
            },
            cameraController: {
              constrainedAxis: false, //解除在南北极区域鼠标操作限制
            },
          },
        })

        //创建三维地球场景
        map = new mars3d.Map('mars3dContainer', mapOptions)

        //创建矢量数据图层
        graphicLayer = new mars3d.layer.GraphicLayer()
        map.addLayer(graphicLayer)

        //加载示例数据
        // eslint-disable-next-line prettier/prettier
        // var hostiryData = {"startDate":"2021-05-31 19:56:18","endDate":"2021-05-31 20:56:18","geojson":{"type":"Feature","properties":{"id":"M-676224DB-E1C7-492B-BD4F-11245263E921","type":"rectangle","style":{"color":"#ffff00","opacity":0.2,"outline":true,"outlineColor":"#ffffff","materialType":"Color","clampToGround":false,"height":-1253.05}},"geometry":{"type":"Polygon","coordinates":[[[76.021252,46.81116,-1253.1],[152.705424,1.598719,-7200.1]]]}}}
        // $('#txtStartTime').val(hostiryData.startDate) //开始时间
        // $('#txtEndTime').val(hostiryData.endDate) //结束时间
        // drawGraphic = map.graphicLayer.loadGeoJSON(hostiryData.geojson)[0]

        initUI()

        $.ajax({
          url: 'http://data.marsgis.cn/file/apidemo/tle-china.json',
          dataType: 'json',
          type: 'get',
          success: function (data) {
            tleArr = data.data
            console.log('卫星数量：' + tleArr.length)
          },
          error: function (data) {
            haoutil.msg('获取空间目标轨道数据异常！')
          },
        })
      }

      function initUI() {
        jeDate('#txtStartTime', {
          theme: {
            bgcolor: '#135b91',
            pnColor: '#00CCFF',
          },
          format: 'YYYY-MM-DD hh:mm:ss',
        })
        jeDate('#txtEndTime', {
          theme: {
            bgcolor: '#135b91',
            pnColor: '#00CCFF',
          },
          format: 'YYYY-MM-DD hh:mm:ss',
        })

        var now = Cesium.JulianDate.toDate(map.clock.currentTime)
        $('#txtStartTime').val(now.format('yyyy-MM-dd HH:mm:ss'))

        now.setMinutes(now.getMinutes() + 60)
        $('#txtEndTime').val(now.format('yyyy-MM-dd HH:mm:ss'))

        //框选查询 矩形
        $('#drawRectangle').click(function () {
          map.graphicLayer.clear()
          map.graphicLayer.startDraw({
            type: 'rectangle',
            style: {
              color: '#ffff00',
              opacity: 0.2,
              outline: true,
              outlineColor: '#ffffff',
            },
            success: function (graphic) {
              drawGraphic = graphic
            },
          })
        })
        //框选查询   多边
        $('#drawPolygon').click(function () {
          map.graphicLayer.clear()
          map.graphicLayer.startDraw({
            type: 'polygon',
            style: {
              color: '#ffff00',
              opacity: 0.2,
              outline: true,
              outlineColor: '#ffffff',
            },
            success: function (graphic) {
              drawGraphic = graphic
            },
          })
        })
        //框选查询   圆
        $('#drawCircle').click(function () {
          map.graphicLayer.clear()
          map.graphicLayer.startDraw({
            type: 'circle',
            style: {
              color: '#ffff00',
              opacity: 0.2,
              outline: true,
              outlineColor: '#ffffff',
            },
            success: function (graphic) {
              drawGraphic = graphic
            },
          })
        })

        $('#drawClear').click(function () {
          map.graphicLayer.clear()
          drawGraphic = null
        })

        $table = $('#table')
        $table.bootstrapTable({
          height: 300,
          singleSelect: true, //单选
          pagination: false,
          iconsPrefix: 'fa',
          columns: [
            {
              field: 'name',
              title: '卫星名称',
              sortable: true,
              editable: false,
              align: 'left',
            },
            {
              field: 'inTime',
              title: '进入时间',
              sortable: true,
              editable: false,
              align: 'left',
            },
            {
              field: 'outTime',
              title: '飞出时间',
              sortable: true,
              editable: false,
              align: 'left',
            },
            {
              field: 'often',
              title: '飞行时长',
              sortable: true,
              editable: false,
              align: 'left',
            },
            {
              field: 'distance',
              title: '飞行距离',
              sortable: true,
              editable: false,
              align: 'left',
            },
          ],
          onClickRow: function (item, $element, field) {
            var graphic = item._graphic
            if (graphic == null) {
              toastr.warning(item.name + ' 无经纬度坐标信息！')
              return
            }
            graphic.flyTo()
          },
        })
      }

      //清除效果
      function clearResult() {
        $table.bootstrapTable('load', [])
        graphicLayer.clear()
      }

      //================卫星过境===================================

      //颜色
      var pointClr = Cesium.Color.fromCssColorString('#ff0000').withAlpha(0.7)

      function startFX() {
        clearResult()

        if (!drawGraphic) {
          haoutil.msg('请先在图上绘制区域')
          return
        }

        var startDate = new Date($('#txtStartTime').val()) //开始时间
        var endDate = new Date($('#txtEndTime').val()) //结束时间

        var startTimes = startDate.getTime()
        var endTimes = endDate.getTime()

        //记录参数值
        console.log(
          JSON.stringify({
            startDate: startDate.format('yyyy-MM-dd HH:mm:ss'),
            endDate: endDate.format('yyyy-MM-dd HH:mm:ss'),
            geojson: drawGraphic.toGeoJSON(),
          })
        )

        //范围相关信息
        var options = {
          startTimes: startTimes,
          endTimes: endTimes,
          graphic: drawGraphic,
        }

        //分析卫星位置
        var newSatelliteArr = [] //存储飞过指定范围的卫星的数据
        for (var ind = 0; ind < tleArr.length; ind++) {
          var item = tleArr[ind]
          var arr = fxOneSatellite(item, options)

          if (arr.length == 0) {
            continue
          }

          item.inAreaPath = arr
          newSatelliteArr.push(item)
        }

        showResult(newSatelliteArr)
      }

      function fxOneSatellite(item, options) {
        var inAreaPath = []
        var lastObj = null

        var graphic = options.graphic
        var startTimes = options.startTimes
        var endTimes = options.endTimes
        var step = 10 * 1000 //插值数

        var nowTime = startTimes
        var position
        while (nowTime <= endTimes) {
          //根据时间计算卫星的位置
          let pos = mars3d.SpaceUtil.getSatellitePosition(item.tle1, item.tle2, nowTime)
          if (!pos) {
            break
          }

          position = pos.position

          //显示点[参考比较结果是否正确]
          var timeStr = new Date(nowTime).format('yyyy-MM-dd HH:mm:ss')
          var primitive = new mars3d.graphic.PointPrimitive({
            position: position,
            style: {
              color: pointClr,
              pixelSize: 3,
            },
            attr: item,
            tooltip: `编号：${item.norad} <br />卫星：${item.name} <br />时间：${timeStr}`,
          })
          graphicLayer.addGraphic(primitive)

          //判断是卫星否在缓冲区内
          var isInPoly = graphic.isInPoly(position)

          // console.log(`${item.name},时间：${timeStr},结果：${isInPoly}`);

          if (lastObj && !lastObj.isInPoly && isInPoly) {
            //表示进入范围
            inAreaPath.push({
              lastPosition: lastObj.position,
              lastTime: lastObj.time,
              time: nowTime,
              position: position,
              inOrOut: 'in',
            })
          }

          if (lastObj && lastObj.isInPoly && !isInPoly) {
            //表示出范围
            inAreaPath.push({
              position: position,
              lastPosition: lastObj.position,
              lastTime: lastObj.time,
              time: nowTime,
              inOrOut: 'out',
            })
            break
          }

          lastObj = {
            position: position,
            isInPoly: isInPoly,
            time: nowTime,
          }
          nowTime += step
        }

        if (lastObj && lastObj.isInPoly) {
          //表示出范围
          inAreaPath.push({
            position: position,
            lastPosition: lastObj.position,
            lastTime: lastObj.time,
            time: nowTime,
            inOrOut: 'out',
          })
        }

        return inAreaPath
      }

      //=====================结果展示==================================

      function showResult(newSatelliteArr) {
        //显示卫星条带
        var tableList = []

        for (var ind = 0; ind < newSatelliteArr.length; ind++) {
          var item = newSatelliteArr[ind]
          var inAreaPath = item.inAreaPath
          if (inAreaPath.length < 2) {
            continue
          }

          var index = 0
          if (inAreaPath[0].inOrOut == 'out') {
            //保证从进入 开始计算
            index = 1
          }

          for (var i = index; i < inAreaPath.length; i = i + 2) {
            var positions = []
            var inTime
            var outTime
            if (inAreaPath[i].inOrOut == 'in' && inAreaPath[i + 1].inOrOut == 'out') {
              var inAttr = inAreaPath[i]
              var outAttr = inAreaPath[i + 1]
              if (inAttr) {
                inTime = new Date(inAttr.lastTime).format('yyyy-M-d HH:mm:ss')
                positions.push(inAttr.lastPosition)
              }
              if (outAttr) {
                positions.push(outAttr.position)
                outTime = new Date(outAttr.time).format('yyyy-M-d HH:mm:ss')
              }
              if (positions.length > 1) {
                var data = {
                  positions: positions,
                  name: item.name,
                  inTime: inTime,
                  outTime: outTime,
                  often: haoutil.str.formatTime((outAttr.time - inAttr.lastTime) / 1000),
                  distance: haoutil.str.formatLength(Cesium.Cartesian3.distance(positions[1], positions[0])),
                }
                tableList.push(data)
                showCorridor(data)
              }
            }
          }
        }
        $table.bootstrapTable('load', tableList)

        haoutil.msg('分析完成，共' + tableList.length + '条过境记录')
      }

      var corridor = []

      function showCorridor(data) {
        var primitive = new mars3d.graphic.CorridorPrimitive({
          positions: data.positions,
          style: {
            width: 6000,
            cornerType: Cesium.CornerType.MITERED, //指定转角处样式
            color: '#00ff00',
            outline: true,
          },
        })
        graphicLayer.addGraphic(primitive)

        var inthtml =
          '<table style="width:280px;">' +
          '<tr><th scope="col" colspan="4"  style="text-align:center;font-size:15px;">信息</th></tr>' +
          '<tr><td >卫星名称：</td><td >' +
          data.name +
          ' </td></tr>' +
          '<tr><td >进入时间：</td><td >' +
          data.inTime +
          ' </td></tr>' +
          '<tr><td >飞出时间：</td><td >' +
          data.outTime +
          ' </td></tr>' +
          '<tr><td >过境时长：</td><td >' +
          data.often +
          ' </td></tr>' +
          '<tr><td >过境距离：</td><td >' +
          data.distance +
          ' </td></tr>' +
          '</table>'
        primitive.bindPopup(inthtml)

        data._graphic = primitive
      }
    </script>
  </body>
</html>
